//
//  NewsController.swift
//  网易新闻
//
//  Created by wl on 15/11/11.
//  Copyright © 2015年 wl. All rights reserved.
//
/***************************************************
*  如果您发现任何BUG,或者有更好的建议或者意见，请您的指教。
*邮箱:wxl19950606@163.com.感谢您的支持
***************************************************/
import UIKit

class NewsController: UIViewController, ChannelBoxDelegate {
    
 // MARK: - 属性
//========================================================
// MARK: 频道列表属性
//========================================================
    @IBOutlet weak var channelScrollView: UIScrollView!
    //var channels: ChannelBox = ChannelBox()
    lazy var channels: ChannelBoxEx = ChannelBoxEx()
    var labelArray: [ChannelLabel] = []
    var currentChannelsLabel: ChannelLabel!
    var maxchannelsCount: Int = 20
    var channelCount: Int = 0
    let labelMargin: CGFloat = 25
//========================================================
// MARK: 新闻列表属性
//========================================================
    @IBOutlet weak var newsContainerView: NewsContainerView!
    var newsListVcArray: [UITableViewController] = []
//========================================================
// MARK: 天气按钮属性
//========================================================
    
    var isShow: Bool = false
    @IBOutlet weak var weatherBtn: UIButton!
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.channels.delegate = self
    }
    
 // MARK: - 初始化方法
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false

        var shareBtn = UIButton(type: UIButtonType.Custom)
        shareBtn = UIButton(frame: CGRectMake(0, 0, 80, 32))
        shareBtn.setTitle("美因苛求", forState: UIControlState.Normal)
        shareBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        let share = UIBarButtonItem(customView: shareBtn)
        
        self.navigationItem.leftBarButtonItem = share
        
        self.tabBarController?.tabBar.tintColor = NAVIGATIONBAR_RED_COLOR
        
        if (!(NSUserDefaults.standardUserDefaults().boolForKey("everLaunched"))) {
            NSUserDefaults.standardUserDefaults().setBool(true, forKey:"everLaunched")
            
           SecondLaunchView.showAtWindow()
            
            
            //判断是否自动播放视频
            NSUserDefaults.standardUserDefaults().setBool(true, forKey:"video_of_on")
            //字体大小
            NSUserDefaults.standardUserDefaults().setObject("16" , forKey:"fontSizeDefaut")
            //是否完成地址
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isCompleteDefaultAddress")
            //是否登录
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "k_UD_isLogin")
           
            NSUserDefaults.standardUserDefaults().synchronize()

            
        }
        if ApplicationDelegate.isLogin(){
            let phone = publicMethod.userName()
            let pass = publicMethod.passWord()
            let token = publicMethod.token()
            DataTool.login(phone, pass: pass, token: token, completionHandler: { (newModel) in
                guard let newDataes = newModel else {
                return
                }
                print(newDataes)
                
            })

        }
    }

    func loadChannelDataDone() {
        self.setupChannelScrollView()
        self.setupNewsContainerView()
        self.showFirstNewsList()
       
    }
    /**
    channelScrollView的一些初始化操作，
    用来创建默认的新闻频道
    */
    func setupChannelScrollView() {
        self.channelCount = self.channels.channels.count
        
        self.channelCount = self.channels.channels.count > maxchannelsCount ? maxchannelsCount : channelCount
        
        let labelX: ([UILabel]) -> CGFloat = {
            (labels: [UILabel]) -> CGFloat in
            
            let lastObj = labels.last
            guard let label = lastObj else {
                return self.labelMargin
            }
            return CGRectGetMaxX(label.frame) + self.labelMargin
        }
        
        for i in 0..<channelCount {
            let label = ChannelLabel()
            label.text = self.channels[i].channelName
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(16)
            label.sizeToFit()
            label.frame.origin.x = labelX(self.labelArray)
            label.frame.origin.y = (self.channelScrollView.bounds.height -  label.bounds.height) * 0.5
            //添加点击事件
            label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(NewsController.channelLabelClick(_:))))
            label.userInteractionEnabled = true
            label.tag = i
            self.labelArray.append(label)
            self.channelScrollView.addSubview(label)
        }
        self.channelScrollView.contentSize = CGSizeMake(labelX(self.labelArray), 0)
    }
    /**
    newsContainerView的一些初始化操作，
    根据默认新闻频道，创建所有可能需要展示的新闻列表
    */
    func setupNewsContainerView() {
        
        for i in 0..<self.channelCount {
            if self.channels[i].channelName == "业内转让" {
                let vc = storyboard?.instantiateViewControllerWithIdentifier("TransferTableViewController") as! TransferTableViewController
                vc.channel = self.channels[i].channelName
                vc.channelUrl = self.channels[i].channelUrl
                self.newsListVcArray.append(vc)
                //成为自控制器，方便以后调用
                self.addChildViewController(vc)
            } else if self.channels[i].channelName == "求职招聘" {
                let vc = storyboard?.instantiateViewControllerWithIdentifier("JoinUsTableViewController") as! JoinUsTableViewController
                vc.channel = self.channels[i].channelName
                vc.channelUrl = self.channels[i].channelUrl
                self.newsListVcArray.append(vc)
                //成为自控制器，方便以后调用
                self.addChildViewController(vc)
            } else if self.channels[i].channelName == "专业院线"{
                let vc = storyboard?.instantiateViewControllerWithIdentifier("specialChannelTC") as! specialChannelTC
                vc.channel = self.channels[i].channelName
                vc.channelUrl = self.channels[i].channelUrl
                self.newsListVcArray.append(vc)
                //成为自控制器，方便以后调用
                self.addChildViewController(vc)
            } else {
                let vc = storyboard?.instantiateViewControllerWithIdentifier("NewsListContorller") as! NewsListContorller
                vc.channel = self.channels[i].channelName
                vc.channelUrl = self.channels[i].channelUrl
                self.newsListVcArray.append(vc)
                //成为自控制器，方便以后调用
                self.addChildViewController(vc)
            }
        }
        
        self.newsContainerView.contentSize = CGSizeMake(UIScreen.mainScreen().bounds.width * CGFloat(self.newsListVcArray.count), 0)
        self.newsContainerView.pagingEnabled = true
        self.newsContainerView.delegate = self
    }
    /**
    显示默认的新闻列表(头条频道)
    */
    func showFirstNewsList() {
        
        let vc = self.newsListVcArray.first!
        self.newsContainerView.showViewInScrollView(vc.tableView, showViewIndex: 0)

        let label = self.labelArray.first!
        currentChannelsLabel = label
        label.scale = 1
        setupNavigationItem(0)
    }
    /**
    频道label的点击手势回调方法，
    当点击事件发生后，将新闻列表切换到被点击label对应的新闻列表
    */
    func channelLabelClick(recognizer: UITapGestureRecognizer) {
    
        let label = recognizer.view as! ChannelLabel
        let index = label.tag
        
        self.currentChannelsLabel.scale = 0
        label.scale = 1
        
        let offsetX = CGFloat(index) * self.newsContainerView.bounds.width
        let offset = CGPointMake(offsetX, 0)
        //这个方法animated为true才会导致scrollViewDidEndScrollingAnimation代理方法被调用
        self.newsContainerView.setContentOffset(offset, animated: false)
        //代码滚动到显示了那一"页"
        self.scrollViewDidEndScrollingAnimation(self.newsContainerView)
        
        setupNavigationItem(index)
    }
}

// MARK: - UIScrollView的代理方法(newsContainerView)

extension NewsController: UIScrollViewDelegate{
    
    /**
    每次滑动newsContainerView都会调用，用来制造频道label的动画效果
    */
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let currentIndex = scrollView.contentOffset.x / scrollView.bounds.width
        let leftIndex = Int(currentIndex)
        let rightIndex = leftIndex + 1

        guard currentIndex > 0 && rightIndex <  self.labelArray.count else {
            return
        }
        let rightScale = currentIndex - CGFloat(leftIndex)
        let leftScale = CGFloat(rightIndex) - currentIndex
        
        let rightLabel = self.labelArray[rightIndex]
        let leftLabel = self.labelArray[leftIndex]

        rightLabel.scale = rightScale
        leftLabel.scale = leftScale
    }
    
    /**
    这个是在newsContainerView减速停止的时候开始执行，
    用来切换需要显示的新闻列表和让频道标签处于合适的位置
    */
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        self.scrollViewDidEndScrollingAnimation(scrollView)
    }
    
    /**
    这个是当用户用代码导致滚动时候调用列如setContentOffset，
    用来切换需要显示的新闻列表和让频道标签处于合适的位置
    */
    func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 让频道标签处于合适的位置
        let currentLabel = self.labelArray[index]
        self.currentChannelsLabel = currentLabel
        var offsetX = currentLabel.center.x - self.channelScrollView.bounds.width * 0.5
        let maxOffset = self.channelScrollView.contentSize.width - self.channelScrollView.bounds.width
        if offsetX > 0{
            offsetX = offsetX > maxOffset ? maxOffset : offsetX
        }else {
            offsetX = 0
        }
        let offset = CGPointMake(offsetX, 0)
        self.channelScrollView.setContentOffset(offset, animated: true)
        
        // 切换需要显示的控制器
        let vc = self.newsListVcArray[index]
        self.newsContainerView.showViewInScrollView(vc.tableView, showViewIndex: index)

        self.setupNavigationItem(index)
    }

}

extension NewsController {
    @IBAction func prepareforUnwind(segue: UIStoryboardSegue) {
        
    }
}

extension NewsController {
    func setupNavigationItem(labelIndex: Int) -> Void {
        let channelName = self.channels[labelIndex].channelName
        NSUserDefaults.standardUserDefaults().setObject(channelName, forKey: "selectedChanelName")
        NSUserDefaults.standardUserDefaults().synchronize()
        
        if channelName == "业内转让" || channelName == "求职招聘"{
            if channelName == "业内转让"{
                let vc = self.newsListVcArray[labelIndex] as! TransferTableViewController
                
                let item=UIBarButtonItem(title: "发布信息", style: UIBarButtonItemStyle.Plain, target: vc, action: #selector(TransferTableViewController.onSendInfoClick))
                var array: [UIBarButtonItem] = []
                array.append(item)
                self.navigationItem.rightBarButtonItems = array
            }else if channelName == "求职招聘"{
                let vc = self.newsListVcArray[labelIndex] as! JoinUsTableViewController
                
                let item=UIBarButtonItem(title: "发布信息", style: UIBarButtonItemStyle.Plain, target: vc, action: #selector(JoinUsTableViewController.onSendInfoClick))
                var array: [UIBarButtonItem] = []
                array.append(item)
                self.navigationItem.rightBarButtonItems = array

            }
        }else if channelName == "产品推荐" || channelName == "行业资讯" || channelName == "专业院线" || channelName == "享乐生活"{
           
            if channelName == "专业院线"{
                
                let vc = self.newsListVcArray[labelIndex] as! specialChannelTC
                var signBtn = UIButton(type: UIButtonType.Custom)
                signBtn = UIButton(frame: CGRectMake(0, 0, 28, 28))
                signBtn.setBackgroundImage(UIImage(named: "sign")!, forState: UIControlState.Normal)
               
                signBtn.addTarget(vc, action: #selector(specialChannelTC.signClick), forControlEvents:  UIControlEvents.TouchUpInside)
                let sign = UIBarButtonItem(customView: signBtn)
              
                
                let searchBtn = UIButton(frame: CGRectMake(0, 0, 24, 24))
                searchBtn.setBackgroundImage(UIImage(named: "search")!, forState: UIControlState.Normal)
                
                searchBtn.addTarget(vc, action: #selector(specialChannelTC.searchClick), forControlEvents:  UIControlEvents.TouchUpInside)
                let search = UIBarButtonItem(customView: searchBtn)
                
                self.navigationItem.rightBarButtonItems = [search,sign]
                
                
                
            }else{
            
            let vc = self.newsListVcArray[labelIndex] as! NewsListContorller
            let signBtn = UIButton(frame: CGRectMake(0, 0, 28, 28))
            signBtn.setBackgroundImage(UIImage(named: "sign")!, forState: UIControlState.Normal)
            signBtn.addTarget(vc, action: #selector(NewsListContorller.signClick), forControlEvents:  UIControlEvents.TouchUpInside)
            let sign = UIBarButtonItem(customView: signBtn)
                
            let searchBtn = UIButton(frame: CGRectMake(0, 0, 24, 24))
            searchBtn.setBackgroundImage(UIImage(named: "search")!, forState: UIControlState.Normal)
            searchBtn.addTarget(vc, action: #selector(NewsListContorller.searchClick), forControlEvents:  UIControlEvents.TouchUpInside)
            let search = UIBarButtonItem(customView: searchBtn)
  
            self.navigationItem.rightBarButtonItems = [search,sign]
                
            }
        }
    }
}

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com